<template>
  <div class="u-page">
    <u--form ref="form" labelPosition="top" labelWidth="100%" :labelStyle="labelStyle" :model="form" :rules="rules">
      <!-- <u-form-item label="返利银行卡号" prop="oldBankCardNo">
        <u--input v-model="form.oldBankCardNo" placeholder="请输入返利银行卡号" clearable></u--input>
      </u-form-item> -->
	  <view class="u-flex mt-2">
	    <text class="">返利银行卡号</text>
		<u-icon class="plus-icon" name="camera" size="48" color="#3c9cff" @click="bankOcr"></u-icon>
	  </view>
	  <text class="tip">请填写曾经接收圣瑞公司返利的银行卡卡号，用于核对您的身份信息。</text>
	  <view>
		  <view class="u-flex mt-2">
			  <u--input v-model="form.oldBankCardNo" placeholder="请输入返利银行卡号" clearable></u--input>
		  </view>
	  </view>

      
      <view>
		  <view class="u-flex mt-2">
		    <text class="">投资凭证票据号</text>
		    <u-icon class="plus-icon" name="plus-circle" size="48" color="#3c9cff" @click="plusBillNo"></u-icon>
		  </view>
		  <text class="tip">请填写您的投资票据号，最多添加20个；点击加号进行添加、点击减号进行删除。</text>
        <view class="u-flex mt-2" v-for="(item, index) in form.billNo" :key="index">
          <u--input v-model="form.billNo[index]" placeholder="请输入票据号" clearable></u--input>
          <u-icon
            v-if="form.billNo.length > 1"
            class="plus-icon"
            name="minus-circle"
            size="48"
            color="#3c9cff"
            @click="minusBillNo(index)"
          ></u-icon>
        </view>
      </view>

      <u-form-item class="mt-2">
        <u-row class="w-100" justify="center">
          <u-col span="6" justify="center">
            <u-button type="primary" shape="circle" @click="confirm"><view>下一步</view></u-button>
          </u-col>
        </u-row>
      </u-form-item>
    </u--form>

    <view>
      <u-modal :show="noticeShow" title="温馨提示">
        <view>
          <view class="font-tip text-indent">{{ tipText }}</view>
        </view>
        <u-button slot="confirmButton" @click="noticeShow = false" type="success" shape="circle">已知晓</u-button>
      </u-modal>
    </view>
  </div>
</template>

<script>
import { baseFont, srStepKey } from '@/common/config.js';
import { saveIdCard } from '@/common/api/mcRegister.js';
import { getAccessToken, bankCardOCR } from '@/common/baiduApi.js';
import { pathToBase64 } from 'image-tools';

const tipText = '由于您报案时登记信息缺失，请补充信息！';
const errorText = '您提供信息有误，请您重新核实您的返利银行卡号或投资凭证票据号，确保信息填报准确！';
export default {
  data() {
    return {
      tipText: tipText,
      preStep: srStepKey.index,
      currentStep: srStepKey.step0_5,
      nextStep: srStepKey.step1,
      labelStyle: { fontSize: baseFont + 'upx', marginBottom: '10upx' },
      name: '',
      resultList: [],
      form: {
        oldBankCardNo: '',
        billNo: [''],
        resultList: [],
      },
      rules: {},
      inputArr: [''],
      noticeShow: true,
    };
  },
  onLoad(options) {
    this.checkMcPage(options);
    this.tipText = tipText;
    // 未传证件号不能进入
    const { idCard = '' } = options;
    if (idCard === '') {
      this.toMcIndex();
    }
    // 未获取到姓名、查找结果不能进入
    const { index: { name = '', idCardNo = '', resultList = [] } = {} } = this.$getMcInfo(idCard);
    if (name === '' || resultList.length === 0) {
      this.toMcIndex();
    }
    this.idCard = idCard;
    this.name = name;
    this.resultList = resultList;
  },
  methods: {
    toStep1Page() {
      uni.reLaunch({
        url: this.$mcStepPath[mcStepKey.step1] + this.buildParams(this.idCard),
      });
    },
    plusBillNo() {
      // this.form.billNo.push('');
	  if (this.form.billNo.length >= 20) {
		  uni.$u.toast('最多添加20个。');
	  } else {
		  this.form.billNo.push('');
	  }
    },
    minusBillNo(index) {
      this.form.billNo.splice(index, 1);
    },
    toNext(resultList){
      this.form.resultList=resultList
      const { state, reason, type, collectFlag } = resultList[0];
      if(state === 1){
        this.form.resultList = resultList;
        this.toNextMcPage(this.idCard);
      }else{
        const cid=resultList.map(item=>item.cid).join(',')
        this.toMcResult(state, reason, this.idCard,cid);
      }
    },
    confirm() {
      let that = this;
      if (!this.form.billNo.some(item => item && item !== '') && this.form.oldBankCardNo === '') {
        uni.$u.toast('请输入返利银行卡号或票据号！');
        return;
      }
      let resultList = [];
      // 校验返利银行卡
      if (this.form.oldBankCardNo && this.form.oldBankCardNo !== '') {
        resultList = this.resultList
          .filter(item => this.form.oldBankCardNo === item.oldBankCardNo)
          .map(item => {
            return {
              cid: item.cid,
              state: item.state,
              reason: item.reason,
              type: item.type,
              collectFlag: item.collectFlag,
              idCardNo: this.idCard,
              billNo: this.form.billNo.join(','),
              oldBankCardNo: this.form.oldBankCardNo,
            };
          });
      }
      // 银行卡查到结果
      if (resultList.length > 0) {
        this.toNext(resultList)
      } else {
        // 校验票据号
        resultList = this.resultList
          .filter(item => {
            const billNo = item.billNo ? item.billNo.split(',') : [];
            if (billNo.length === 0) {
              return false;
            }
            return billNo.filter(value => this.form.billNo.indexOf(value) > -1).length > 0;
          })
          .map(item => {
            return {
              cid: item.cid,
              state: item.state,
              reason: item.reason,
              type: item.type,
              collectFlag: item.collectFlag,
              idCardNo: this.idCard,
              billNo: this.form.billNo.join(','),
              oldBankCardNo: this.form.oldBankCardNo,
            };
          });
        if (resultList.length > 0) {
          this.toNext(resultList);
        } else {
          this.tipText = errorText;
          this.noticeShow = true;
        }
      }
    },
	async bankOcr() {
		let that = this;
		that.accessToken = await getAccessToken();
		setTimeout(() => {
			uni.chooseImage({
			  count: 1,
			  sizeType: ['compressed'],
			  sourceType: ['camera'],
			  success(res) {
				  uni.showLoading({
				    title: '处理中，请稍后...',
				  });
				  const tempFilePaths = res.tempFilePaths;
				  pathToBase64(tempFilePaths[0]).then(path => {
				    let imageBase64 = path.replace(/^data:image\/\w+;base64,/, '');
				    if (imageBase64) {
				      // uni.$u.toast('1比1');
					 bankCardOCR(imageBase64, that.accessToken).then(bank => {
						  const data = bank.data;
						  const bankCardNo = data.result.bank_card_number;
						  that.form.oldBankCardNo = bankCardNo;
						  uni.hideLoading();
					  });
				    }
				  });
			  },
			  fail: error => {
			    uni.$u.toast(JSON.stringify(error));
			  }
			})
		})
	}
  },
};
</script>

<style scoped lang="scss">
.plus-icon {
  margin-left: 40upx;
  cursor: pointer;
  font-weight: bold;
}
</style>
